package com.qyhl.module_home.city.bestone.ontype;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.github.promeg.pinyinhelper.Pinyin;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.module_home.city.bestone.SearchAdapter;
import com.qyhl.module_home.utils.IndexBarView;
import com.qyhl.module_home.utils.PinyinComparator;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.home.BestoneItemTypeBean;
import com.weavey.loading.lib.LoadingLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

@Route(path = ARouterPathConstant.BESTONE_TYPE_LIST)
public class BestoneTypeActivity extends BaseActivity implements BestoneTypeContract.BestoneTypeView {
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.loadMask)
    LoadingLayout loadMask;
    @BindView(R2.id.searchList)
    RecyclerView searchList;
    @BindView(R2.id.alllist)
    RecyclerView alllist;
    @BindView(R2.id.searchClear)
    ImageView searchClear;
    @BindView(R2.id.gosearch)
    ImageView gosearch;
    @BindView(R2.id.searchText)
    EditText searchText;
    @BindView(R2.id.indexbar)
    IndexBarView indexbar;

    private String typeId;
    /**
     * 控制能否搜索
     */
    private boolean isCanSearch = false;

    private BestoneTypeContract.BestoneTypePresenter presenter;
    private ArrayList<BestoneItemTypeBean> allDatas;
    private ArrayList<BestoneItemTypeBean> serachDatas;
    private AlllistAdapter allAdapter;
    private SearchAdapter searchAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.home_activity_bestone_type;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        inits();
    }

    private void inits() {
        typeId = getIntent().getExtras().getString("typeid");
        title.setText(getIntent().getExtras().getString("title"));

        loadMask.setStatus(LoadingLayout.Loading);

        presenter = new BestoneTypePresenter(this);

        initAllList();

        alllist.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                indexbar.moveToPositionFormTag(String.valueOf(allDatas.get(((LinearLayoutManager) (alllist.getLayoutManager())).findFirstVisibleItemPosition()).getFirstPinYin()));
            }
        });

        indexbar.setIndexOnClickListener((selectPosition, selectTag) -> {
            for (int i = 0; i < allDatas.size(); i++) {
                if (String.valueOf(allDatas.get(i).getFirstPinYin()).equals(selectTag)) {
                    ((LinearLayoutManager) (alllist.getLayoutManager())).scrollToPositionWithOffset(i, 0);
                }
            }
        });

        back.setOnClickListener(v -> finish());

        //列表获取失败点击重试
        loadMask.setOnReloadListener(view -> {
            loadMask.setStatus(LoadingLayout.Loading);
            presenter.getData(typeId);
        });

        //搜索输入监听
        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(searchText.getText().toString())) {
                    searchClear.setVisibility(View.GONE);
                    showTypeList(true);
                    loadMask.setStatus(LoadingLayout.Success);
                } else {
                    searchClear.setVisibility(View.VISIBLE);
                }
            }
        });

        //搜索清空输入
        searchClear.setOnClickListener(v -> searchText.setText(""));

        //搜索
        gosearch.setOnClickListener(v -> {
            if (isCanSearch) {
                String text = searchText.getText().toString();
                if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(text.trim())) {
                    text = text.trim();
                    if (serachDatas == null) {
                        initSearchList();
                    }
                    searchAdapter.setInputText(text);
                    showTypeList(false);
                    setSearch(text);
                }
            }
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
        });

        presenter.getData(typeId);
    }

    @Override
    protected void setListener() {

    }

    /**
     * 在本地列表中搜索数据
     */
    private void setSearch(String text) {
        serachDatas.clear();
        for (BestoneItemTypeBean bean : allDatas) {
            if (bean.getTitle().contains(text) || bean.getPhone().contains(text)) {
                serachDatas.add(bean);
            }
        }
        if (serachDatas.isEmpty()) {
            loadMask.setEmptyImage(0);
            loadMask.setEmptyText("无搜索结果");
            loadMask.setStatus(LoadingLayout.Empty);
        } else {
            searchAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 搜索列表初始化
     */
    private void initAllList() {
        allDatas = new ArrayList<>();
        //纵向线性布局
        alllist.setLayoutManager(new LinearLayoutManager(this));
        alllist.addItemDecoration(new BestoneItemDecoration(allDatas, this));
        allAdapter = new AlllistAdapter(this, allDatas);
        alllist.setAdapter(allAdapter);
    }

    /**
     * 搜索列表初始化
     */
    private void initSearchList() {
        serachDatas = new ArrayList<>();
        //纵向线性布局
        searchList.setLayoutManager(new LinearLayoutManager(this));
        searchAdapter = new SearchAdapter(this, serachDatas);
        searchList.setAdapter(searchAdapter);
    }

    /**
     * 是否显示类型列表布局
     */
    private void showTypeList(boolean isType) {
        if (isType) {
            alllist.setVisibility(View.VISIBLE);
            indexbar.setVisibility(View.VISIBLE);
            searchList.setVisibility(View.GONE);
        } else {
            alllist.setVisibility(View.GONE);
            indexbar.setVisibility(View.GONE);
            searchList.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getDataError(String msg) {
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
    }

    @Override
    public void getDataSuccess(List<BestoneItemTypeBean> data) {
        if (data != null && !data.isEmpty()) {
            isCanSearch = true;
            allDatas.clear();
            allDatas.addAll(data);

            for (BestoneItemTypeBean bean : allDatas) {
                String all = Pinyin.toPinyin(bean.getTitle(), "").toUpperCase();
                bean.setAllPinYin(all);
                char first = all.charAt(0);
                if (first >= 'A' && first <= 'Z') {
                    bean.setFirstPinYin(first);
                } else {
                    bean.setFirstPinYin('#');
                }
            }

            Collections.sort(allDatas, new PinyinComparator());

            allAdapter.notifyDataSetChanged();
            loadMask.setStatus(LoadingLayout.Success);
            indexbar.moveToPositionFormTag(String.valueOf(allDatas.get(0).getFirstPinYin()));
        } else {
            loadMask.setStatus(LoadingLayout.Empty);
        }
    }
}
